from datetime import datetime
from myApp.model.db import db
from myApp.model.message_model import Message


class Room(db.Model):
    __tablename__ = 'room'

    id = db.Column(db.String(100), primary_key=True, comment='对话ID')
    name = db.Column(db.String(300))
    user_id = db.Column(db.String(100))
    status = db.Column(db.Integer, default=1, nullable=False, comment='状态')
    create_time = db.Column(db.DateTime, default=datetime.utcnow)
    update_time = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    messages = db.relationship('Message', backref='room', lazy=True)

    # serialize
    def serialize(self):
        return {
            'id': self.id,
            'name': self.name,
            'path': self.id,
            'data': [],
            'user_id': self.user_id,
            'status': self.status,
            'create_time': self.create_time.strftime('%Y-%m-%d %H:%M:%S'),
            'update_time': self.update_time.strftime('%Y-%m-%d %H:%M:%S')
        }

    # @staticmethod
    # def update_room_update_time(room_id):
    #     room = Room.query.filter_by(id=room_id).first()
    #     if room:
    #         current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    #         room.update_time = current_time  # 更新房间的更新时间
    #         db.session.commit()

    # 无：创建房间，有：更新房间时间
    @staticmethod
    def create_room(id, name, user_id):
        existing_room = Room.query.filter_by(id=id).first()
        if existing_room is None:
            # 限制房间的标题长度
            if len(name) > 30:
                name = name[:30]
            room = Room(id=id, name=name, user_id=user_id)
            db.session.add(room)
            db.session.commit()
            return True
        else:
            current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            existing_room.update_time = current_time  # 更新房间的更新时间
            db.session.commit()
            return False

    @staticmethod
    def get_active_rooms_by_user_id(user_id):
        rooms = Room.query.filter_by(user_id=user_id, status=1).order_by(Room.update_time.asc()).all()
        return rooms

    @staticmethod
    def update_room(room, **kwargs):
        for key, value in kwargs.items():
            setattr(room, key, value)
        db.session.commit()

    @staticmethod
    def delete_room(room_id):
        Message.delete_message_by_room_id(room_id)
        room = Room.query.filter_by(id=room_id).first()
        if room:
            room.status = 0
            db.session.commit()
        else:
            print(f"房间不存在 {room_id} ")

    @staticmethod
    def delete_room_user(user_id):
        rooms = Room.query.filter_by(user_id=user_id).all()
        for room in rooms:
            Message.delete_message_by_room_id(room.id)
            room.status = 0
        db.session.commit()


